package com.wgspring.service;

import com.wgspring.mapper.PhotographMapper;
import com.wgspring.model.Photograph;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;

@Service
public class PhotographService {

    @Autowired
    private PhotographMapper photographMapper;

    public void addPhoto(MultipartFile file) throws IOException {
        //获得原文件名
        String originalFilename = file.getOriginalFilename();
        System.out.println(originalFilename);
        //设置新文件名
        String newFilename = UUID.randomUUID().toString().replace("-", "") + originalFilename.substring(originalFilename.lastIndexOf("."));
        //设置保存路径.
        String path = ResourceBundle.getBundle("db").getString("file.uploadurl");
        //检查该路径对应的目录是否存在. 如果不存在则创建目录
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        String filePath = path + newFilename;
        System.out.println("上传文件已保存到 " + filePath);

        //保存文件
        File dest = new File(filePath);
        file.transferTo(dest);

        //保存数据库
        Photograph photograph = new Photograph();
        photograph.setId(UUID.randomUUID().toString().replace("-", ""));
        photograph.setTime(new Date().getTime());
        photograph.setUrl(newFilename);
        photographMapper.insertPhotograph(photograph);

    }


    public List<Photograph> getOnedayPhotographsBeforeTime(Long time) {
        long end = time;
        //找出比该时间更早的一张图片
        Photograph photograph = photographMapper.selectOnePhotographBeforeTime(end);
        //计算该图片的时间所在的那一天的整天时间范围
        if (photograph == null) {
            return null;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(photograph.getTime());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        long start = calendar.getTimeInMillis();
        //根据该范围找图片
        return photographMapper.selectPhotographsByTime(start, end);
    }
}
